<?php

namespace mpend\modules\user\controllers;

use Yii;
use mpend\components\Controller;
use common\models\user\UserConnect;
use common\helpers\ArrayHelper;

/**
 * 用户收件地址相关接口
 * AddressController for the `user` module
 */
class WechatController extends Controller {

    /**
     * @inheritdoc
     */
    protected function rules() {
        return [
            [
                'allow' => true,
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    protected function verbs() {
        return [
            'index' => ['GET'],
            'view' => ['GET'],
            'delete' => ['DELETE'],
            '*' => ['POST'],
        ];
    }

    /**
     * 地址列表
     * @return mixed
     */
    public function actionIndex($id) {
        $connect = UserConnect::findOrFail($id);
        $data = $connect->getCacheToken();

        $openid = $connect->openid;
        $accessToken = ArrayHelper::getValue($data, 'access_token');
        if (!$openid || !$accessToken) {
            return false;
        }
        try {
            /* @var $wechat \common\components\wechat\MpWechat */
            $wechat = Yii::$app->wechat;
            $userinfo = $wechat->getSnsUserInfo($openid, $accessToken);
            if ($userinfo === false) {
                $refresh_token = ArrayHelper::getValue($data, 'refresh_token');
                $refreshData = $wechat->refreshOauth2AccessToken($refresh_token);
                $connect->setCacheToken($refreshData);

                $accessToken = ArrayHelper::getValue($refreshData, 'access_token');
                $userinfo = $wechat->getSnsUserInfo($openid, $accessToken);
            }
        } catch (\yii\base\Exception $e) {
            parent::error($e->getMessage());
        }

        if ($userinfo === false) {
            return false;
        }

        $avatar = ArrayHelper::getValue($userinfo, 'headimgurl');
        $location = ArrayHelper::getValue($userinfo, 'country') . ArrayHelper::getValue($userinfo, 'province') . ArrayHelper::getValue($userinfo, 'city');
        $gender = ArrayHelper::getValue($userinfo, 'sex');
        $nickname = ArrayHelper::getValue($userinfo, 'nickname');

        return compact('nickname', 'gender', 'avatar', 'location');
    }

}
